const express = require('express')
const db = require('../../db')
const path = require('path')
const router = express.Router()

const videoSuffix = [
  'mp4',
  'mov',
  'avi',
  'wmv',
  'flv',
  '3gp',
  'mvk'
]

router.get('/min/:message_id', (req, res) => {
  const { message_id } = req.params
  // console.log('message_id: ', message_id)

  const getFileName = 'select content from easy_chat.messages where message_id = ?'
  db.query(getFileName, message_id, (err, result) => {
    if (err) res.errHandle(err)

    let lastPath = result[0].content
    if (videoSuffix.includes(result[0].content.split('.')[1])) {
      lastPath = result[0].content.split('.')[0] + '.png'
    }
    const filePath = path.join(__dirname, 'uploads', 'min_' + lastPath)
    // console.log('filePath: ', filePath)

    res.sendFile(filePath)
  })
})

router.get('/ori/:message_id', (req, res) => {
  const { message_id } = req.params
  // console.log('message_id: ', message_id)

  const getFileName = 'select content from easy_chat.messages where message_id = ?'
  db.query(getFileName, message_id, (err, result) => {
    if (err) res.errHandle(err)

    const filePath = path.join(__dirname, 'uploads', result[0].content)
    // console.log('filePath: ', filePath)

    res.sendFile(filePath)
  })
})

module.exports = router
